<template>
  <div class="container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>编辑用户</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="user" 
        :rules="rules" 
        label-width="120px" 
        style="max-width: 600px;"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="user.userName" disabled />
        </el-form-item>
        
        <el-form-item label="新密码" prop="password">
          <el-input 
            v-model="user.password" 
            type="password" 
            placeholder="留空则不修改密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="user.confirmPassword" 
            type="password" 
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="管理的宿舍楼" prop="dormBuildId">
          <el-select 
            v-model="user.dormBuildId" 
            clearable
            placeholder="请选择管理的宿舍楼"
            style="width: 100%"
          >
            <el-option
              v-for="dorm in dorms"
              :key="dorm.dormBuildId"
              :label="dorm.dormBuildName"
              :value="dorm.dormBuildId"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'

export default {
  data() {
    const validatePassword = (rule, value, callback) => {
      if (this.user.password && value !== this.user.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    
    return {
      user: {
        id: null,
        userName: '',
        password: '',
        confirmPassword: '',
        dormBuildId: null
      },
      dorms: [],
      rules: {
        password: [
          { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validatePassword, trigger: 'blur' }
        ]
      }
    }
  },
  async created() {
    await Promise.all([this.fetchUser(), this.fetchDorms()])
  },
  methods: {
    async fetchUser() {
      try {
        const userId = this.$route.params.id
        const response = await axios.get(
          `http://localhost:8080/UserMgr_Web_exploded/users/${userId}`,
          {
            headers: {
              'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
          }
        )
        this.user = {
          ...response.data,
          password: '',
          confirmPassword: ''
        }
      } catch (error) {
        ElMessage.error('获取用户信息失败')
        console.error(error)
      }
    },
    async fetchDorms() {
      try {
        const response = await axios.get(
          "http://localhost:8080/UserMgr_Web_exploded/dorms",
          {
            headers: {
              'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
          }
        )
        this.dorms = response.data
      } catch (error) {
        ElMessage.error('获取宿舍楼列表失败')
        console.error(error)
      }
    },
    async submitForm() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          const loading = ElLoading.service({ text: '正在保存...', lock: true })
          
          try {
            // 如果密码为空，则不更新密码
            const updateData = {
              ...this.user,
              password: this.user.password || undefined,
              confirmPassword: undefined // 不发送到后端
            }
            
            const response = await axios.put(
              `http://localhost:8080/UserMgr_Web_exploded/users/${this.user.id}`,
              updateData,
              {
                headers: {
                  'Authorization': 'Bearer ' + localStorage.getItem('token')
                }
              }
            )
            
            if (response.data.success) {
              ElMessage.success('用户信息更新成功')
              this.$router.push('/users')
            } else {
              ElMessage.error(response.data.message || '更新失败')
            }
          } catch (error) {
            if (error.response) {
              if (error.response.status === 401) {
                ElMessage.error('登录已过期，请重新登录')
                this.$router.push('/login')
              } else {
                ElMessage.error(error.response.data.message || '更新失败')
              }
            } else {
              ElMessage.error('网络错误，请检查网络连接')
            }
            console.error(error)
          } finally {
            loading.close()
          }
        }
      })
    },
    resetForm() {
      this.fetchUser()
    },
    goBack() {
      this.$router.push('/users')
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>